"use client"
import { FC, createContext } from "react"
import { toast as sonnerToast } from "sonner"
import { AlertCircle, CheckCircle, Info, X } from "lucide-react"

type Props = {
  children: React.ReactNode
}

type ToastProps = {
  id: string | number // toast id
  type?: string // 消息类型
  title?: string // 消息标题
  description?: string // 消息描述
  duration?: number // 消息持续时间
}

export type Options = Omit<ToastProps, "id" | "type">

type ToastContext = {
  showInfo: (options: Options) => void
  showSuccess: (options: Options) => void
  showError: (options: Options) => void
}

export const ToastContext = createContext<ToastContext | undefined>(undefined)

/**
 * 自定义 Toast
 */
export const ToastProvider: FC<Props> = (props) => {
  const { children } = props

  /**
   * 自定义 Sonner Toast
   */
  const toast = (toastProps: Omit<ToastProps, "id">) => {
    const { type = "info", title, description, duration } = toastProps

    return sonnerToast.custom(
      (id) => {
        return <Toast id={id} title={title} type={type} description={description} />
      },
      { duration: duration }
    )
  }

  /**
   * 自定义的 toast 组件
   */
  const Toast = (props: ToastProps) => {
    const { id, title, description, type } = props

    const renderIcon = () => {
      switch (type) {
        case "success":
          return <CheckCircle className="h-5 w-5 text-green-500" />
        case "error":
          return <AlertCircle className="h-5 w-5 text-red-500" />
        case "info":
          return <Info className="h-5 w-5 text-blue-500" />
        default:
          return <Info className="h-5 w-5 text-blue-500" />
      }
    }

    return (
      <div className="relative rounded-lg border p-4 shadow-lg transition-all duration-300 ease-in-out w-full max-w-md min-w-[356px]">
        <div className="flex items-start">
          <div className="flex-shrink-0">{renderIcon()}</div>
          <div className="ml-3 flex-1">
            {title && <h4 className="text-sm font-medium text-gray-900 dark:text-gray-100">{title}</h4>}
            {description && <p className="mt-1 text-sm text-gray-500 dark:text-gray-400">{description}</p>}
          </div>
          <div className="flex-shrink-0" onClick={() => sonnerToast.dismiss(id)}>
            <X className="h-5 w-5 text-gray-400 dark:text-gray-500 cursor-pointer" />
          </div>
        </div>
      </div>
    )
  }

  const showInfo = (options: Options) => {
    return toast({ type: "info", ...options })
  }

  const showSuccess = (options: Options) => {
    return toast({ type: "success", ...options })
  }

  const showError = (options: Options) => {
    return toast({ type: "error", ...options })
  }

  const value = {
    showInfo,
    showSuccess,
    showError
  }

  return <ToastContext.Provider value={value}>{children}</ToastContext.Provider>
}
